package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.RecordAlbumDao;
import jumpingnotes.model.entity.RecordAlbum;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

public class RecordAlbumHibernateDao extends GenericHibernateDao<RecordAlbum> implements RecordAlbumDao
{
	public RecordAlbumHibernateDao()
	{
		super(RecordAlbum.class);
	}

	@SuppressWarnings("unchecked")
	public List<RecordAlbum> findRecordAlbumByBookId(final int bookId, final int firstResult, final int maxResults)
	{
		return (List<RecordAlbum>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Criteria criteria = session.createCriteria(RecordAlbum.class);
				criteria.createAlias("book", "book");
				criteria.add(Restrictions.eq("book.bookId", bookId));
				criteria.setFetchMode("member", FetchMode.JOIN);
				criteria.addOrder(Order.desc("albumRating"));

				if (firstResult >= 0)
					criteria.setFirstResult(firstResult);
				if (maxResults > 0)
					criteria.setMaxResults(maxResults);

				return criteria.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<RecordAlbum> findRecordAlbumByMemberId(final int memberId, final int firstResult, final int maxResults)
	{
		return (List<RecordAlbum>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Criteria criteria = session.createCriteria(RecordAlbum.class);
				criteria.createAlias("member", "member");
				criteria.add(Restrictions.eq("member.memberId", memberId));
				criteria.setFetchMode("member", FetchMode.JOIN);
				criteria.addOrder(Order.desc("albumRating"));

				if (firstResult >= 0)
					criteria.setFirstResult(firstResult);
				if (maxResults > 0)
					criteria.setMaxResults(maxResults);

				return criteria.list();
			}
		});
	}

	@Override
	public RecordAlbum findById(final int recordAlbumId)
	{
		return (RecordAlbum) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Criteria criteria = session.createCriteria(RecordAlbum.class);
				criteria.add(Restrictions.eq("recordAlbumId", recordAlbumId));
				criteria.setFetchMode("member", FetchMode.JOIN);
				return criteria.uniqueResult();
			}
		});
	}
}
